home *** CD-ROM | disk | FTP | other *** search
/ Clickx 53 / Clickx 53.iso / software / onmisbaretool / firefoxv301 / Firefox Setup 3.0.1.exe / nonlocalized / components / nsBrowserContentHandler.js < prev    next >
Encoding:
JavaScript  |  2008-07-02  |  31.9 KB  |  917 lines

  1. //@line 37 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\nsBrowserContentHandler.js"
  2.  
  3. const nsISupports            = Components.interfaces.nsISupports;
  4.  
  5. const nsIBrowserDOMWindow    = Components.interfaces.nsIBrowserDOMWindow;
  6. const nsIBrowserHandler      = Components.interfaces.nsIBrowserHandler;
  7. const nsIBrowserHistory      = Components.interfaces.nsIBrowserHistory;
  8. const nsIChannel             = Components.interfaces.nsIChannel;
  9. const nsICommandLine         = Components.interfaces.nsICommandLine;
  10. const nsICommandLineHandler  = Components.interfaces.nsICommandLineHandler;
  11. const nsIContentHandler      = Components.interfaces.nsIContentHandler;
  12. const nsIDocShellTreeItem    = Components.interfaces.nsIDocShellTreeItem;
  13. const nsIDOMChromeWindow     = Components.interfaces.nsIDOMChromeWindow;
  14. const nsIDOMWindow           = Components.interfaces.nsIDOMWindow;
  15. const nsIFactory             = Components.interfaces.nsIFactory;
  16. const nsIFileURL             = Components.interfaces.nsIFileURL;
  17. const nsIHttpProtocolHandler = Components.interfaces.nsIHttpProtocolHandler;
  18. const nsIInterfaceRequestor  = Components.interfaces.nsIInterfaceRequestor;
  19. const nsINetUtil             = Components.interfaces.nsINetUtil;
  20. const nsIPrefBranch          = Components.interfaces.nsIPrefBranch;
  21. const nsIPrefLocalizedString = Components.interfaces.nsIPrefLocalizedString;
  22. const nsISupportsString      = Components.interfaces.nsISupportsString;
  23. const nsIURIFixup            = Components.interfaces.nsIURIFixup;
  24. const nsIWebNavigation       = Components.interfaces.nsIWebNavigation;
  25. const nsIWindowMediator      = Components.interfaces.nsIWindowMediator;
  26. const nsIWindowWatcher       = Components.interfaces.nsIWindowWatcher;
  27. const nsICategoryManager     = Components.interfaces.nsICategoryManager;
  28. const nsIWebNavigationInfo   = Components.interfaces.nsIWebNavigationInfo;
  29. const nsIBrowserSearchService = Components.interfaces.nsIBrowserSearchService;
  30. const nsICommandLineValidator = Components.interfaces.nsICommandLineValidator;
  31.  
  32. const NS_BINDING_ABORTED = 0x804b0002;
  33. const NS_ERROR_WONT_HANDLE_CONTENT = 0x805d0001;
  34. const NS_ERROR_ABORT = Components.results.NS_ERROR_ABORT;
  35.  
  36. const URI_INHERITS_SECURITY_CONTEXT = nsIHttpProtocolHandler
  37.                                         .URI_INHERITS_SECURITY_CONTEXT;
  38.  
  39. function shouldLoadURI(aURI) {
  40.   if (aURI && !aURI.schemeIs("chrome"))
  41.     return true;
  42.  
  43.   dump("*** Preventing external load of chrome: URI into browser window\n");
  44.   dump("    Use -chrome <uri> instead\n");
  45.   return false;
  46. }
  47.  
  48. function resolveURIInternal(aCmdLine, aArgument) {
  49.   var uri = aCmdLine.resolveURI(aArgument);
  50.  
  51.   if (!(uri instanceof nsIFileURL)) {
  52.     return uri;
  53.   }
  54.  
  55.   try {
  56.     if (uri.file.exists())
  57.       return uri;
  58.   }
  59.   catch (e) {
  60.     Components.utils.reportError(e);
  61.   }
  62.  
  63.   // We have interpreted the argument as a relative file URI, but the file
  64.   // doesn't exist. Try URI fixup heuristics: see bug 290782.
  65.  
  66.   try {
  67.     var urifixup = Components.classes["@mozilla.org/docshell/urifixup;1"]
  68.                              .getService(nsIURIFixup);
  69.  
  70.     uri = urifixup.createFixupURI(aArgument, 0);
  71.   }
  72.   catch (e) {
  73.     Components.utils.reportError(e);
  74.   }
  75.  
  76.   return uri;
  77. }
  78.  
  79. const OVERRIDE_NONE        = 0;
  80. const OVERRIDE_NEW_PROFILE = 1;
  81. const OVERRIDE_NEW_MSTONE  = 2;
  82. /**
  83.  * Determines whether a home page override is needed.
  84.  * Returns:
  85.  *  OVERRIDE_NEW_PROFILE if this is the first run with a new profile.
  86.  *  OVERRIDE_NEW_MSTONE if this is the first run with a build with a different
  87.  *                      Gecko milestone (i.e. right after an upgrade).
  88.  *  OVERRIDE_NONE otherwise.
  89.  */
  90. function needHomepageOverride(prefb) {
  91.   var savedmstone = null;
  92.   try {
  93.     savedmstone = prefb.getCharPref("browser.startup.homepage_override.mstone");
  94.   } catch (e) {}
  95.  
  96.   if (savedmstone == "ignore")
  97.     return OVERRIDE_NONE;
  98.  
  99.   var mstone = Components.classes["@mozilla.org/network/protocol;1?name=http"]
  100.                          .getService(nsIHttpProtocolHandler).misc;
  101.  
  102.   if (mstone != savedmstone) {
  103.     prefb.setCharPref("browser.startup.homepage_override.mstone", mstone);
  104.     return (savedmstone ? OVERRIDE_NEW_MSTONE : OVERRIDE_NEW_PROFILE);
  105.   }
  106.  
  107.   return OVERRIDE_NONE;
  108. }
  109.  
  110. // Copies a pref override file into the user's profile pref-override folder,
  111. // and then tells the pref service to reload it's default prefs.
  112. function copyPrefOverride() {
  113.   try {
  114.     var fileLocator = Components.classes["@mozilla.org/file/directory_service;1"]
  115.                                 .getService(Components.interfaces.nsIProperties);
  116.     const NS_APP_EXISTING_PREF_OVERRIDE = "ExistingPrefOverride";
  117.     var prefOverride = fileLocator.get(NS_APP_EXISTING_PREF_OVERRIDE,
  118.                                        Components.interfaces.nsIFile);
  119.     if (!prefOverride.exists())
  120.       return; // nothing to do
  121.  
  122.     const NS_APP_PREFS_OVERRIDE_DIR     = "PrefDOverride";
  123.     var prefOverridesDir = fileLocator.get(NS_APP_PREFS_OVERRIDE_DIR,
  124.                                            Components.interfaces.nsIFile);
  125.  
  126.     // Check for any existing pref overrides, and remove them if present
  127.     var existingPrefOverridesFile = prefOverridesDir.clone();
  128.     existingPrefOverridesFile.append(prefOverride.leafName);
  129.     if (existingPrefOverridesFile.exists())
  130.       existingPrefOverridesFile.remove(false);
  131.  
  132.     prefOverride.copyTo(prefOverridesDir, null);
  133.  
  134.     // Now that we've installed the new-profile pref override file,
  135.     // re-read the default prefs.
  136.     var prefSvcObs = Components.classes["@mozilla.org/preferences-service;1"]
  137.                                .getService(Components.interfaces.nsIObserver);
  138.     prefSvcObs.observe(null, "reload-default-prefs", null);
  139.   } catch (ex) {
  140.     Components.utils.reportError(ex);
  141.   }
  142. }
  143.  
  144. // Flag used to indicate that the arguments to openWindow can be passed directly.
  145. const NO_EXTERNAL_URIS = 1;
  146.  
  147. function openWindow(parent, url, target, features, args, noExternalArgs) {
  148.   var wwatch = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  149.                          .getService(nsIWindowWatcher);
  150.  
  151.   if (noExternalArgs == NO_EXTERNAL_URIS) {
  152.     // Just pass in the defaultArgs directly
  153.     var argstring;
  154.     if (args) {
  155.       argstring = Components.classes["@mozilla.org/supports-string;1"]
  156.                             .createInstance(nsISupportsString);
  157.       argstring.data = args;
  158.     }
  159.  
  160.     return wwatch.openWindow(parent, url, target, features, argstring);
  161.   }
  162.   
  163.   // Pass an array to avoid the browser "|"-splitting behavior.
  164.   var argArray = Components.classes["@mozilla.org/supports-array;1"]
  165.                     .createInstance(Components.interfaces.nsISupportsArray);
  166.  
  167.   // add args to the arguments array
  168.   var stringArgs = null;
  169.   if (args instanceof Array) // array
  170.     stringArgs = args;
  171.   else if (args) // string
  172.     stringArgs = [args];
  173.  
  174.   if (stringArgs) {
  175.     // put the URIs into argArray
  176.     var uriArray = Components.classes["@mozilla.org/supports-array;1"]
  177.                        .createInstance(Components.interfaces.nsISupportsArray);
  178.     stringArgs.forEach(function (uri) {
  179.       var sstring = Components.classes["@mozilla.org/supports-string;1"]
  180.                               .createInstance(nsISupportsString);
  181.       sstring.data = uri;
  182.       uriArray.AppendElement(sstring);
  183.     });
  184.     argArray.AppendElement(uriArray);
  185.   } else {
  186.     argArray.AppendElement(null);
  187.   }
  188.  
  189.   // Pass these as null to ensure that we always trigger the "single URL"
  190.   // behavior in browser.js's BrowserStartup (which handles the window
  191.   // arguments)
  192.   argArray.AppendElement(null); // charset
  193.   argArray.AppendElement(null); // referer
  194.   argArray.AppendElement(null); // postData
  195.   argArray.AppendElement(null); // allowThirdPartyFixup
  196.  
  197.   return wwatch.openWindow(parent, url, target, features, argArray);
  198. }
  199.  
  200. function openPreferences() {
  201.   var features = "chrome,titlebar,toolbar,centerscreen,dialog=no";
  202.   var url = "chrome://browser/content/preferences/preferences.xul";
  203.  
  204.   var win = getMostRecentWindow("Browser:Preferences");
  205.   if (win) {
  206.     win.focus();
  207.   } else {
  208.     openWindow(null, url, "_blank", features);
  209.   }
  210. }
  211.  
  212. function getMostRecentWindow(aType) {
  213.   var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  214.                      .getService(nsIWindowMediator);
  215.   return wm.getMostRecentWindow(aType);
  216. }
  217.  
  218. //@line 261 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\nsBrowserContentHandler.js"
  219.  
  220. // this returns the most recent non-popup browser window
  221. function getMostRecentBrowserWindow() {
  222.   var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  223.                      .getService(Components.interfaces.nsIWindowMediator);
  224.  
  225. //@line 281 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\nsBrowserContentHandler.js"
  226.   var windowList = wm.getZOrderDOMWindowEnumerator("navigator:browser", true);
  227.   if (!windowList.hasMoreElements())
  228.     return null;
  229.  
  230.   var win = windowList.getNext();
  231.   while (win.document.documentElement.getAttribute("chromehidden")) {
  232.     if (!windowList.hasMoreElements()) 
  233.       return null;
  234.  
  235.     win = windowList.getNext();
  236.   }
  237. //@line 293 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\nsBrowserContentHandler.js"
  238.  
  239.   return win;
  240. }
  241.  
  242. function doSearch(searchTerm, cmdLine) {
  243.   var ss = Components.classes["@mozilla.org/browser/search-service;1"]
  244.                      .getService(nsIBrowserSearchService);
  245.  
  246.   var submission = ss.defaultEngine.getSubmission(searchTerm, null);
  247.  
  248.   // fill our nsISupportsArray with uri-as-wstring, null, null, postData
  249.   var sa = Components.classes["@mozilla.org/supports-array;1"]
  250.                      .createInstance(Components.interfaces.nsISupportsArray);
  251.  
  252.   var wuri = Components.classes["@mozilla.org/supports-string;1"]
  253.                        .createInstance(Components.interfaces.nsISupportsString);
  254.   wuri.data = submission.uri.spec;
  255.  
  256.   sa.AppendElement(wuri);
  257.   sa.AppendElement(null);
  258.   sa.AppendElement(null);
  259.   sa.AppendElement(submission.postData);
  260.  
  261.   // XXXbsmedberg: use handURIToExistingBrowser to obey tabbed-browsing
  262.   // preferences, but need nsIBrowserDOMWindow extensions
  263.  
  264.   var wwatch = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  265.                          .getService(nsIWindowWatcher);
  266.  
  267.   return wwatch.openWindow(null, nsBrowserContentHandler.chromeURL,
  268.                            "_blank",
  269.                            "chrome,dialog=no,all" +
  270.                              nsBrowserContentHandler.getFeatures(cmdLine),
  271.                            sa);
  272. }
  273.  
  274. var nsBrowserContentHandler = {
  275.   /* helper functions */
  276.  
  277.   mChromeURL : null,
  278.  
  279.   get chromeURL() {
  280.     if (this.mChromeURL) {
  281.       return this.mChromeURL;
  282.     }
  283.  
  284.     var prefb = Components.classes["@mozilla.org/preferences-service;1"]
  285.                           .getService(nsIPrefBranch);
  286.     this.mChromeURL = prefb.getCharPref("browser.chromeURL");
  287.  
  288.     return this.mChromeURL;
  289.   },
  290.  
  291.   /* nsISupports */
  292.   QueryInterface : function bch_QI(iid) {
  293.     if (!iid.equals(nsISupports) &&
  294.         !iid.equals(nsICommandLineHandler) &&
  295.         !iid.equals(nsIBrowserHandler) &&
  296.         !iid.equals(nsIContentHandler) &&
  297.         !iid.equals(nsICommandLineValidator) &&
  298.         !iid.equals(nsIFactory))
  299.       throw Components.results.NS_ERROR_NO_INTERFACE;
  300.  
  301.     return this;
  302.   },
  303.  
  304.   /* nsICommandLineHandler */
  305.   handle : function bch_handle(cmdLine) {
  306.     if (cmdLine.handleFlag("browser", false)) {
  307.       // Passing defaultArgs, so use NO_EXTERNAL_URIS
  308.       openWindow(null, this.chromeURL, "_blank",
  309.                  "chrome,dialog=no,all" + this.getFeatures(cmdLine),
  310.                  this.defaultArgs, NO_EXTERNAL_URIS);
  311.       cmdLine.preventDefault = true;
  312.     }
  313.  
  314.     try {
  315.       var remoteCommand = cmdLine.handleFlagWithParam("remote", true);
  316.     }
  317.     catch (e) {
  318.       throw NS_ERROR_ABORT;
  319.     }
  320.  
  321.     if (remoteCommand != null) {
  322.       try {
  323.         var a = /^\s*(\w+)\(([^\)]*)\)\s*$/.exec(remoteCommand);
  324.         var remoteVerb;
  325.         if (a) {
  326.           remoteVerb = a[1].toLowerCase();
  327.           var remoteParams = [];
  328.           var sepIndex = a[2].lastIndexOf(",");
  329.           if (sepIndex == -1)
  330.             remoteParams[0] = a[2];
  331.           else {
  332.             remoteParams[0] = a[2].substring(0, sepIndex);
  333.             remoteParams[1] = a[2].substring(sepIndex + 1);
  334.           }
  335.         }
  336.  
  337.         switch (remoteVerb) {
  338.         case "openurl":
  339.         case "openfile":
  340.           // openURL(<url>)
  341.           // openURL(<url>,new-window)
  342.           // openURL(<url>,new-tab)
  343.  
  344.           // First param is the URL, second param (if present) is the "target"
  345.           // (tab, window)
  346.           var url = remoteParams[0];
  347.           var target = nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW;
  348.           if (remoteParams[1]) {
  349.             var targetParam = remoteParams[1].toLowerCase()
  350.                                              .replace(/^\s*|\s*$/g, "");
  351.             if (targetParam == "new-tab")
  352.               target = nsIBrowserDOMWindow.OPEN_NEWTAB;
  353.             else if (targetParam == "new-window")
  354.               target = nsIBrowserDOMWindow.OPEN_NEWWINDOW;
  355.             else {
  356.               // The "target" param isn't one of our supported values, so
  357.               // assume it's part of a URL that contains commas.
  358.               url += "," + remoteParams[1];
  359.             }
  360.           }
  361.  
  362.           var uri = resolveURIInternal(cmdLine, url);
  363.           handURIToExistingBrowser(uri, target, cmdLine);
  364.           break;
  365.  
  366.         case "xfedocommand":
  367.           // xfeDoCommand(openBrowser)
  368.           if (remoteParams[0].toLowerCase() != "openbrowser")
  369.             throw NS_ERROR_ABORT;
  370.  
  371.           // Passing defaultArgs, so use NO_EXTERNAL_URIS
  372.           openWindow(null, this.chromeURL, "_blank",
  373.                      "chrome,dialog=no,all" + this.getFeatures(cmdLine),
  374.                      this.defaultArgs, NO_EXTERNAL_URIS);
  375.           break;
  376.  
  377.         default:
  378.           // Somebody sent us a remote command we don't know how to process:
  379.           // just abort.
  380.           throw "Unknown remote command.";
  381.         }
  382.  
  383.         cmdLine.preventDefault = true;
  384.       }
  385.       catch (e) {
  386.         Components.utils.reportError(e);
  387.         // If we had a -remote flag but failed to process it, throw
  388.         // NS_ERROR_ABORT so that the xremote code knows to return a failure
  389.         // back to the handling code.
  390.         throw NS_ERROR_ABORT;
  391.       }
  392.     }
  393.  
  394.     var uriparam;
  395.     try {
  396.       while ((uriparam = cmdLine.handleFlagWithParam("new-window", false))) {
  397.         var uri = resolveURIInternal(cmdLine, uriparam);
  398.         if (!shouldLoadURI(uri))
  399.           continue;
  400.         openWindow(null, this.chromeURL, "_blank",
  401.                    "chrome,dialog=no,all" + this.getFeatures(cmdLine),
  402.                    uri.spec);
  403.         cmdLine.preventDefault = true;
  404.       }
  405.     }
  406.     catch (e) {
  407.       Components.utils.reportError(e);
  408.     }
  409.  
  410.     try {
  411.       while ((uriparam = cmdLine.handleFlagWithParam("new-tab", false))) {
  412.         var uri = resolveURIInternal(cmdLine, uriparam);
  413.         handURIToExistingBrowser(uri, nsIBrowserDOMWindow.OPEN_NEWTAB, cmdLine);
  414.         cmdLine.preventDefault = true;
  415.       }
  416.     }
  417.     catch (e) {
  418.       Components.utils.reportError(e);
  419.     }
  420.  
  421.     var chromeParam = cmdLine.handleFlagWithParam("chrome", false);
  422.     if (chromeParam) {
  423.  
  424.       // Handle the old preference dialog URL separately (bug 285416)
  425.       if (chromeParam == "chrome://browser/content/pref/pref.xul") {
  426.         openPreferences();
  427.         cmdLine.preventDefault = true;
  428.       } else try {
  429.         // only load URIs which do not inherit chrome privs
  430.         var features = "chrome,dialog=no,all" + this.getFeatures(cmdLine);
  431.         var uri = resolveURIInternal(cmdLine, chromeParam);
  432.         var netutil = Components.classes["@mozilla.org/network/util;1"]
  433.                                 .getService(nsINetUtil);
  434.         if (!netutil.URIChainHasFlags(uri, URI_INHERITS_SECURITY_CONTEXT)) {
  435.           openWindow(null, uri.spec, "_blank", features);
  436.           cmdLine.preventDefault = true;
  437.         }
  438.       }
  439.       catch (e) {
  440.         Components.utils.reportError(e);
  441.       }
  442.     }
  443.     if (cmdLine.handleFlag("preferences", false)) {
  444.       openPreferences();
  445.       cmdLine.preventDefault = true;
  446.     }
  447.     if (cmdLine.handleFlag("silent", false))
  448.       cmdLine.preventDefault = true;
  449.  
  450.     var searchParam = cmdLine.handleFlagWithParam("search", false);
  451.     if (searchParam) {
  452.       doSearch(searchParam, cmdLine);
  453.       cmdLine.preventDefault = true;
  454.     }
  455.  
  456. //@line 512 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\nsBrowserContentHandler.js"
  457.     // Handle "? searchterm" for Windows Vista start menu integration
  458.     for (var i = cmdLine.length - 1; i >= 0; --i) {
  459.       var param = cmdLine.getArgument(i);
  460.       if (param.match(/^\? /)) {
  461.         cmdLine.removeArguments(i, i);
  462.         cmdLine.preventDefault = true;
  463.  
  464.         searchParam = param.substr(2);
  465.         doSearch(searchParam, cmdLine);
  466.       }
  467.     }
  468. //@line 524 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\nsBrowserContentHandler.js"
  469.   },
  470.  
  471.   helpInfo : "  -browser            Open a browser window.\n",
  472.  
  473.   /* nsIBrowserHandler */
  474.  
  475.   get defaultArgs() {
  476.     var prefb = Components.classes["@mozilla.org/preferences-service;1"]
  477.                           .getService(nsIPrefBranch);
  478.     var formatter = Components.classes["@mozilla.org/toolkit/URLFormatterService;1"]
  479.                               .getService(Components.interfaces.nsIURLFormatter);
  480.  
  481.     var overridePage = "";
  482.     var haveUpdateSession = false;
  483.     try {
  484.       switch (needHomepageOverride(prefb)) {
  485.         case OVERRIDE_NEW_PROFILE:
  486.           // New profile
  487.           overridePage = formatter.formatURLPref("startup.homepage_welcome_url");
  488.           break;
  489.         case OVERRIDE_NEW_MSTONE:
  490.           // Existing profile, new build
  491.           copyPrefOverride();
  492.  
  493.           // Check whether we have a session to restore. If we do, we assume
  494.           // that this is an "update" session.
  495.           var ss = Components.classes["@mozilla.org/browser/sessionstartup;1"]
  496.                              .getService(Components.interfaces.nsISessionStartup);
  497.           haveUpdateSession = ss.doRestore();
  498.           overridePage = formatter.formatURLPref("startup.homepage_override_url");
  499.           break;
  500.     }
  501.     } catch (ex) {}
  502.  
  503.     // formatURLPref might return "about:blank" if getting the pref fails
  504.     if (overridePage == "about:blank")
  505.       overridePage = "";
  506.  
  507.     var startPage = "";
  508.     try {
  509.       var choice = prefb.getIntPref("browser.startup.page");
  510.       if (choice == 1 || choice == 3)
  511.         startPage = this.startPage;
  512.  
  513.       if (choice == 2)
  514.         startPage = Components.classes["@mozilla.org/browser/global-history;2"]
  515.                               .getService(nsIBrowserHistory).lastPageVisited;
  516.     } catch (e) {
  517.       Components.utils.reportError(e);
  518.     }
  519.  
  520.     if (startPage == "about:blank")
  521.       startPage = "";
  522.  
  523.     // Only show the startPage if we're not restoring an update session.
  524.     if (overridePage && startPage && !haveUpdateSession)
  525.       return overridePage + "|" + startPage;
  526.  
  527.     return overridePage || startPage || "about:blank";
  528.   },
  529.  
  530.   get startPage() {
  531.     var prefb = Components.classes["@mozilla.org/preferences-service;1"]
  532.                           .getService(nsIPrefBranch);
  533.  
  534.     var uri = prefb.getComplexValue("browser.startup.homepage",
  535.                                     nsIPrefLocalizedString).data;
  536.  
  537.     if (!uri) {
  538.       prefb.clearUserPref("browser.startup.homepage");
  539.       uri = prefb.getComplexValue("browser.startup.homepage",
  540.                                   nsIPrefLocalizedString).data;
  541.     }
  542.                                 
  543.     var count;
  544.     try {
  545.       count = prefb.getIntPref("browser.startup.homepage.count");
  546.     }
  547.     catch (e) {
  548.       return uri;
  549.     }
  550.  
  551.     for (var i = 1; i < count; ++i) {
  552.       try {
  553.         var page = prefb.getComplexValue("browser.startup.homepage." + i,
  554.                                          nsIPrefLocalizedString).data;
  555.         uri += "\n" + page;
  556.       }
  557.       catch (e) {
  558.       }
  559.     }
  560.  
  561.     return uri;
  562.   },
  563.  
  564.   mFeatures : null,
  565.  
  566.   getFeatures : function bch_features(cmdLine) {
  567.     if (this.mFeatures === null) {
  568.       this.mFeatures = "";
  569.  
  570.       try {
  571.         var width = cmdLine.handleFlagWithParam("width", false);
  572.         var height = cmdLine.handleFlagWithParam("height", false);
  573.  
  574.         if (width)
  575.           this.mFeatures += ",width=" + width;
  576.         if (height)
  577.           this.mFeatures += ",height=" + height;
  578.       }
  579.       catch (e) {
  580.       }
  581.     }
  582.  
  583.     return this.mFeatures;
  584.   },
  585.  
  586.   /* nsIContentHandler */
  587.  
  588.   handleContent : function bch_handleContent(contentType, context, request) {
  589.     try {
  590.       var webNavInfo = Components.classes["@mozilla.org/webnavigation-info;1"]
  591.                                  .getService(nsIWebNavigationInfo);
  592.       if (!webNavInfo.isTypeSupported(contentType, null)) {
  593.         throw NS_ERROR_WONT_HANDLE_CONTENT;
  594.       }
  595.     } catch (e) {
  596.       throw NS_ERROR_WONT_HANDLE_CONTENT;
  597.     }
  598.  
  599.     request.QueryInterface(nsIChannel);
  600.     handURIToExistingBrowser(request.URI,
  601.       nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW, null);
  602.     request.cancel(NS_BINDING_ABORTED);
  603.   },
  604.  
  605.   /* nsICommandLineValidator */
  606.   validate : function bch_validate(cmdLine) {
  607.     // Other handlers may use osint so only handle the osint flag if the url
  608.     // flag is also present and the command line is valid.
  609.     var osintFlagIdx = cmdLine.findFlag("osint", false);
  610.     var urlFlagIdx = cmdLine.findFlag("url", false);
  611.     if (urlFlagIdx > -1 && (osintFlagIdx > -1 ||
  612.         cmdLine.state == nsICommandLine.STATE_REMOTE_EXPLICIT)) {
  613.       var urlParam = cmdLine.getArgument(urlFlagIdx + 1);
  614.       if (cmdLine.length != urlFlagIdx + 2 || /firefoxurl:/.test(urlParam))
  615.         throw NS_ERROR_ABORT;
  616.       cmdLine.handleFlag("osint", false)
  617.     }
  618.   },
  619.  
  620.   /* nsIFactory */
  621.   createInstance: function bch_CI(outer, iid) {
  622.     if (outer != null)
  623.       throw Components.results.NS_ERROR_NO_AGGREGATION;
  624.  
  625.     return this.QueryInterface(iid);
  626.   },
  627.     
  628.   lockFactory : function bch_lock(lock) {
  629.     /* no-op */
  630.   }
  631. };
  632.  
  633. const bch_contractID = "@mozilla.org/browser/clh;1";
  634. const bch_CID = Components.ID("{5d0ce354-df01-421a-83fb-7ead0990c24e}");
  635. const CONTRACTID_PREFIX = "@mozilla.org/uriloader/content-handler;1?type=";
  636.  
  637. function handURIToExistingBrowser(uri, location, cmdLine)
  638. {
  639.   if (!shouldLoadURI(uri))
  640.     return;
  641.  
  642.   var navWin = getMostRecentBrowserWindow();
  643.   if (!navWin) {
  644.     // if we couldn't load it in an existing window, open a new one
  645.     openWindow(null, nsBrowserContentHandler.chromeURL, "_blank",
  646.                "chrome,dialog=no,all" + nsBrowserContentHandler.getFeatures(cmdLine),
  647.                uri.spec);
  648.     return;
  649.   }
  650.  
  651.   var navNav = navWin.QueryInterface(nsIInterfaceRequestor)
  652.                      .getInterface(nsIWebNavigation);
  653.   var rootItem = navNav.QueryInterface(nsIDocShellTreeItem).rootTreeItem;
  654.   var rootWin = rootItem.QueryInterface(nsIInterfaceRequestor)
  655.                         .getInterface(nsIDOMWindow);
  656.   var bwin = rootWin.QueryInterface(nsIDOMChromeWindow).browserDOMWindow;
  657.   bwin.openURI(uri, null, location,
  658.                nsIBrowserDOMWindow.OPEN_EXTERNAL);
  659. }
  660.  
  661.  
  662. var nsDefaultCommandLineHandler = {
  663.   /* nsISupports */
  664.   QueryInterface : function dch_QI(iid) {
  665.     if (!iid.equals(nsISupports) &&
  666.         !iid.equals(nsICommandLineHandler) &&
  667.         !iid.equals(nsIFactory))
  668.       throw Components.results.NS_ERROR_NO_INTERFACE;
  669.  
  670.     return this;
  671.   },
  672.  
  673.   // List of uri's that were passed via the command line without the app
  674.   // running and have already been handled. This is compared against uri's
  675.   // opened using DDE on Win32 so we only open one of the requests.
  676.   _handledURIs: [ ],
  677. //@line 733 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\nsBrowserContentHandler.js"
  678.   _haveProfile: false,
  679. //@line 735 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\nsBrowserContentHandler.js"
  680.  
  681.   /* nsICommandLineHandler */
  682.   handle : function dch_handle(cmdLine) {
  683.     var urilist = [];
  684.  
  685. //@line 741 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\nsBrowserContentHandler.js"
  686.     // If we don't have a profile selected yet (e.g. the Profile Manager is
  687.     // displayed) we will crash if we open an url and then select a profile. To
  688.     // prevent this handle all url command line flags and set the command line's
  689.     // preventDefault to true to prevent the display of the ui. The initial
  690.     // command line will be retained when nsAppRunner calls LaunchChild though
  691.     // urls launched after the initial launch will be lost.
  692.     if (!this._haveProfile) {
  693.       try {
  694.         // This will throw when a profile has not been selected.
  695.         var fl = Components.classes["@mozilla.org/file/directory_service;1"]
  696.                            .getService(Components.interfaces.nsIProperties);
  697.         var dir = fl.get("ProfD", Components.interfaces.nsILocalFile);
  698.         this._haveProfile = true;
  699.       }
  700.       catch (e) {
  701.         while ((ar = cmdLine.handleFlagWithParam("url", false))) { }
  702.         cmdLine.preventDefault = true;
  703.       }
  704.     }
  705. //@line 761 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\nsBrowserContentHandler.js"
  706.  
  707.     try {
  708.       var ar;
  709.       while ((ar = cmdLine.handleFlagWithParam("url", false))) {
  710.         var found = false;
  711.         var uri = resolveURIInternal(cmdLine, ar);
  712.         // count will never be greater than zero except on Win32.
  713.         var count = this._handledURIs.length;
  714.         for (var i = 0; i < count; ++i) {
  715.           if (this._handledURIs[i].spec == uri.spec) {
  716.             this._handledURIs.splice(i, 1);
  717.             found = true;
  718.             cmdLine.preventDefault = true;
  719.             break;
  720.           }
  721.         }
  722.         if (!found) {
  723.           urilist.push(uri);
  724.           // The requestpending command line flag is only used on Win32.
  725.           if (cmdLine.handleFlag("requestpending", false) &&
  726.               cmdLine.state == nsICommandLine.STATE_INITIAL_LAUNCH)
  727.             this._handledURIs.push(uri)
  728.         }
  729.       }
  730.     }
  731.     catch (e) {
  732.       Components.utils.reportError(e);
  733.     }
  734.  
  735.     count = cmdLine.length;
  736.  
  737.     for (i = 0; i < count; ++i) {
  738.       var curarg = cmdLine.getArgument(i);
  739.       if (curarg.match(/^-/)) {
  740.         Components.utils.reportError("Warning: unrecognized command line flag " + curarg + "\n");
  741.         // To emulate the pre-nsICommandLine behavior, we ignore
  742.         // the argument after an unrecognized flag.
  743.         ++i;
  744.       } else {
  745.         try {
  746.           urilist.push(resolveURIInternal(cmdLine, curarg));
  747.         }
  748.         catch (e) {
  749.           Components.utils.reportError("Error opening URI '" + curarg + "' from the command line: " + e + "\n");
  750.         }
  751.       }
  752.     }
  753.  
  754.     if (urilist.length) {
  755.       if (cmdLine.state != nsICommandLine.STATE_INITIAL_LAUNCH &&
  756.           urilist.length == 1) {
  757.         // Try to find an existing window and load our URI into the
  758.         // current tab, new tab, or new window as prefs determine.
  759.         try {
  760.           handURIToExistingBrowser(urilist[0], nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW, cmdLine);
  761.           return;
  762.         }
  763.         catch (e) {
  764.         }
  765.       }
  766.  
  767.       var URLlist = urilist.filter(shouldLoadURI).map(function (u) u.spec);
  768.       if (URLlist.length) {
  769.         openWindow(null, nsBrowserContentHandler.chromeURL, "_blank",
  770.                    "chrome,dialog=no,all" + nsBrowserContentHandler.getFeatures(cmdLine),
  771.                    URLlist);
  772.       }
  773.  
  774.     }
  775.     else if (!cmdLine.preventDefault) {
  776.       // Passing defaultArgs, so use NO_EXTERNAL_URIS
  777.       openWindow(null, nsBrowserContentHandler.chromeURL, "_blank",
  778.                  "chrome,dialog=no,all" + nsBrowserContentHandler.getFeatures(cmdLine),
  779.                  nsBrowserContentHandler.defaultArgs, NO_EXTERNAL_URIS);
  780.     }
  781.   },
  782.  
  783.   // XXX localize me... how?
  784.   helpInfo : "Usage: firefox [-flags] [<url>]\n",
  785.  
  786.   /* nsIFactory */
  787.   createInstance: function dch_CI(outer, iid) {
  788.     if (outer != null)
  789.       throw Components.results.NS_ERROR_NO_AGGREGATION;
  790.  
  791.     return this.QueryInterface(iid);
  792.   },
  793.     
  794.   lockFactory : function dch_lock(lock) {
  795.     /* no-op */
  796.   }
  797. };
  798.  
  799. const dch_contractID = "@mozilla.org/browser/final-clh;1";
  800. const dch_CID = Components.ID("{47cd0651-b1be-4a0f-b5c4-10e5a573ef71}");
  801.  
  802. var Module = {
  803.   /* nsISupports */
  804.   QueryInterface: function mod_QI(iid) {
  805.     if (iid.equals(Components.interfaces.nsIModule) ||
  806.         iid.equals(Components.interfaces.nsISupports))
  807.       return this;
  808.  
  809.     throw Components.results.NS_ERROR_NO_INTERFACE;
  810.   },
  811.  
  812.   /* nsIModule */
  813.   getClassObject: function mod_getco(compMgr, cid, iid) {
  814.     if (cid.equals(bch_CID))
  815.       return nsBrowserContentHandler.QueryInterface(iid);
  816.  
  817.     if (cid.equals(dch_CID))
  818.       return nsDefaultCommandLineHandler.QueryInterface(iid);
  819.  
  820.     throw Components.results.NS_ERROR_NO_INTERFACE;
  821.   },
  822.     
  823.   registerSelf: function mod_regself(compMgr, fileSpec, location, type) {
  824.     if (Components.classes["@mozilla.org/xre/app-info;1"]) {
  825.       // Don't register these if Firefox is launching a XULRunner application
  826.       const FIREFOX_UID = "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}";
  827.       var appInfo = Components.classes["@mozilla.org/xre/app-info;1"]
  828.                               .getService(Components.interfaces.nsIXULAppInfo);
  829.       if (appInfo.ID != FIREFOX_UID)
  830.         return;
  831.     }
  832.  
  833.     var compReg =
  834.       compMgr.QueryInterface( Components.interfaces.nsIComponentRegistrar );
  835.  
  836.     compReg.registerFactoryLocation( bch_CID,
  837.                                      "nsBrowserContentHandler",
  838.                                      bch_contractID,
  839.                                      fileSpec,
  840.                                      location,
  841.                                      type );
  842.     compReg.registerFactoryLocation( dch_CID,
  843.                                      "nsDefaultCommandLineHandler",
  844.                                      dch_contractID,
  845.                                      fileSpec,
  846.                                      location,
  847.                                      type );
  848.  
  849.     function registerType(contentType) {
  850.       compReg.registerFactoryLocation( bch_CID,
  851.                                        "Browser Cmdline Handler",
  852.                                        CONTRACTID_PREFIX + contentType,
  853.                                        fileSpec,
  854.                                        location,
  855.                                        type );
  856.     }
  857.  
  858.     registerType("text/html");
  859.     registerType("application/vnd.mozilla.xul+xml");
  860. //@line 916 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\nsBrowserContentHandler.js"
  861.     registerType("image/svg+xml");
  862. //@line 918 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\nsBrowserContentHandler.js"
  863.     registerType("text/rdf");
  864.     registerType("text/xml");
  865.     registerType("application/xhtml+xml");
  866.     registerType("text/css");
  867.     registerType("text/plain");
  868.     registerType("image/gif");
  869.     registerType("image/jpeg");
  870.     registerType("image/jpg");
  871.     registerType("image/png");
  872.     registerType("image/bmp");
  873.     registerType("image/x-icon");
  874.     registerType("image/vnd.microsoft.icon");
  875.     registerType("image/x-xbitmap");
  876.     registerType("application/http-index-format");
  877.  
  878.     var catMan = Components.classes["@mozilla.org/categorymanager;1"]
  879.                            .getService(nsICategoryManager);
  880.  
  881.     catMan.addCategoryEntry("command-line-handler",
  882.                             "m-browser",
  883.                             bch_contractID, true, true);
  884.     catMan.addCategoryEntry("command-line-handler",
  885.                             "x-default",
  886.                             dch_contractID, true, true);
  887.     catMan.addCategoryEntry("command-line-validator",
  888.                             "b-browser",
  889.                             bch_contractID, true, true);
  890.   },
  891.     
  892.   unregisterSelf : function mod_unregself(compMgr, location, type) {
  893.     var compReg = compMgr.QueryInterface(nsIComponentRegistrar);
  894.     compReg.unregisterFactoryLocation(bch_CID, location);
  895.     compReg.unregisterFactoryLocation(dch_CID, location);
  896.  
  897.     var catMan = Components.classes["@mozilla.org/categorymanager;1"]
  898.                            .getService(nsICategoryManager);
  899.  
  900.     catMan.deleteCategoryEntry("command-line-handler",
  901.                                "m-browser", true);
  902.     catMan.deleteCategoryEntry("command-line-handler",
  903.                                "x-default", true);
  904.     catMan.deleteCategoryEntry("command-line-validator",
  905.                                "b-browser", true);
  906.   },
  907.  
  908.   canUnload: function(compMgr) {
  909.     return true;
  910.   }
  911. };
  912.  
  913. // NSGetModule: Return the nsIModule object.
  914. function NSGetModule(compMgr, fileSpec) {
  915.   return Module;
  916. }
  917.